#include <iostream>
#include <assert.h>
#include <vector>
#include <unistd.h>
#include <stdlib.h>
#include <sys/wait.h>
#include <sys/types.h>
#include "Task.hpp"

using namespace std;

#define PROCESS_NUM 5

int waitCommand(int waitFd, bool &quit)
{
    char32_t command = 0;
    ssize_t s = read(waitFd, &command, sizeof(command));
    if (s == 0)
    {
        quit = true;
        return -1;
    }
    assert(s == sizeof(uint32_t));
    assert(s == sizeof(char32_t));
    return command;
}

void sendAndWakeup(pid_t who, int fd, uint32_t command)
{
    write(fd, &command, sizeof(command));
    cout << "main process: call process " << who << " execute " << desc[command] << " through " << fd << endl;
}

int main()
{
    load();
    // pid , pipefd
    vector<pair<pid_t, int>> slots;
    // 先创建多个进程
    for (int i = 0; i < PROCESS_NUM; i++)
    {
        // 创建管道
        int pipefd[2] = {0}; /* int pipe(int pipefd[2]) */
        int n = pipe(pipefd);
        assert(n != -1);
        (void)n; // 代表n被使用 去警告

        pid_t id = fork();
        assert(id != -1);
        // 子进程让他进行读取
        if (id == 0)
        {
            // 关闭写端
            close(pipefd[1]);
            // 子进程
            while (true)
            {
                // pipefd[0]
                bool quit = false;
                int command = waitCommand(pipefd[0],quit);
                if (quit)
                    break;
                // 执行对应的命令
                if (command >= 0 && command < handlerSize())
                {
                    callbacks[command]();
                }
                else
                {
                    cout << "非法command: " << command << endl;
                }
            }
            exit(1);
        }

        // 父进程 - 写
        close(pipefd[0]);
        slots.push_back(pair<pid_t, int>(id, pipefd[1]));
        while (true)
        {
            int select;
            int command;
            cout << "############################################" << endl;
            cout << "#   1. show funcitons      2.send command  #" << endl;
            cout << "############################################" << endl;
            cout << "Please Select> ";
            cin >> select;
            if (select == 1)
                showHandler();
            else if (select == 2)
            {
                cout << "Enter Your Command> ";
                // 选择任务
                cin >> command;
                // 选择进程
                int choice = rand() % slots.size();
                // 把任务给指定的进程
                sendAndWakeup(slots[choice].first, slots[choice].second, command);
            }
            else
            {
            }
        }
    }

    // 关闭fd,结束所有进程
    // 关闭fd, 所有的子进程都会退出
    for (const auto &slot : slots)
    {
        close(slot.second);
    }

    // 回收所有的子进程信息
    for (const auto &slot : slots)
    {
        waitpid(slot.first, nullptr, 0);
    }
}
